package com.derek.ucd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.derek.ucd.smartonfacebook.R;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;



public class Pages extends Activity {

	String[] allpages;
	
	@SuppressWarnings("unused")
	@Override
    public void onCreate(Bundle savedInstanceState) {
		
		ListView list = null;
		
		
		super.onCreate(savedInstanceState);
    	setContentView(R.layout.pages);
    	
		Intent intent = getIntent();
	    String category = "";
	    if (intent != null) {
	        Bundle extras = intent.getExtras();
	        if (extras != null) {
	        	category = extras.getString("category"); 	        	
	        	
	            // TODO: Allow language change 
	            String APIRoot = "https://en.wikiquote.org/w/api.php?";
	            String QueryPages = "action=query&list=categorymembers&format=json&cmprop=title&cmtype=page&cmlimit=50&cmtitle=Category%3A";
	        	
	            // Create the httpclient
	            HttpClient httpclient = new DefaultHttpClient();
	            HttpGet httpget = null;
				httpget = new HttpGet(APIRoot + QueryPages + category.replace(" ", "%20"));
	            HttpResponse response;
	            // Declare a return string
	            String returnString = null;
	            
	        	try {        	 
	                response = httpclient.execute(httpget);
	                 if(response.getStatusLine().getStatusCode() == 200){
	                    // Connection was established. Get the content. 
	                    HttpEntity entity = response.getEntity();
	                    if (entity != null) {
	                        // A Simple JSON Response Read
	                        InputStream instream = entity.getContent();
	                        // Load the requested page converted to a string into a JSONObject.
	                        JSONObject tmp = new JSONObject(convertStreamToString(instream));
	                        // Close the stream.
	                        instream.close();

	    					String query = tmp.getString("query");
	    					JSONObject queryJSON = new JSONObject(query);
	                        JSONArray allPagesJSON = queryJSON.getJSONArray("categorymembers");

	                        allpages = new String[allPagesJSON.length()];
	                        for(int i = 0; i < allPagesJSON.length(); i++) {
	                        	allpages[i] = allPagesJSON.getString(i).substring(17, (allPagesJSON.getString(i)).length()-2);
	                        }
	                        list = (ListView) findViewById(R.id.listViewPages);       
	                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, allpages);
	                         // Assign adapter to ListView
	                        list.setAdapter(adapter);
	                    }
	                    
	                    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	                	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {               
	                		
	                			Intent i = new Intent(Pages.this, quotes.class);
	                			i.putExtra("page", allpages[position]);
	                			startActivity(i);

	                	}
	                	});
	               
	                }
	                else {
	                    // code here for a response other than 200.  A response 200 means the web page was OK
	                    // Other codes include 404 - not found, 301 - redirect etc...
	                    // Display the response line.
	                    returnString = "Unable to load page - " + response.getStatusLine();
	                }
	            }
	             catch (Exception e) {
	     			// TODO Auto-generated catch block
	     			e.printStackTrace();
	     		}    
	        }
	    }
	}

	    
	    private static String convertStreamToString(InputStream is) {
	        /*
	         * To convert the InputStream to String we use the BufferedReader.readLine()
	         * method. We iterate until the BufferedReader return null which means
	         * there's no more data to read. Each line will appended to a StringBuilder
	         * and returned as String.
	         */
	        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	        StringBuilder sb = new StringBuilder();
	 
	        String line = null;
	        try {
	            while ((line = reader.readLine()) != null) {
	                sb.append(line + "\n");
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                is.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	        return sb.toString();
	    }
}
	    
